'use strict';

var model = require('../model/district.js');
var debug = require('debug')('district');

var Dao = function() {}

Dao.prototype.save = function*(json) {
	var pid = json.pid || null;
	var item =  {
		ad_code: json.ad_code,
		area_code: json.area_code,
		city_code: json.city_code,
		name: json.name,
		pid: pid,
		subid: json.subid,
		level: json.level,
		loc: {
			type: 'Point',
			coordinates: json.center
		}
	}

	var entity = new model(item);
	var result = yield entity.save();
	var _id = result._id;
	if (pid) { // update pid
		yield this.updateSubid(pid, _id);
	}

	return result;
}

Dao.prototype.updateSubid = function*(pid, aSubid) {
	yield model.findOneAndUpdate({
		_id: pid
	}, {
		$addToSet: {
			subid: aSubid
		}
	});
}


// 存储数组
Dao.prototype.saveMany = function*(json) {
	debug('saveMany', json);
	if (!Array.isArray(json)) {
		json = [json];
	}

	for (var i = 0; i < json.length; i++) {
		yield this.saveTree(json[i]);
	}
	return true;
}

// 存储树状结构
Dao.prototype.saveTree = function*(tree) {
	debug('saveTree', tree);
	if (!tree) return;

	var entiry = {
		ad_code: tree.adcode,
		area_code: tree.areacode,
		city_code: tree.citycode,
		name: tree.name,
		center: tree.center.split(','),
		pid: tree.pid || null,
		subid: []
	};

	var result = yield this.save(entiry);
	if (tree.districts && tree.districts.length > 0) {
		tree.districts.forEach(function(item) {
			item.pid = result._id;
		});

		yield this.saveMany(tree.districts);
	}
}

Dao.prototype.findById = function*(id) {
	debug('dao findById, id=' + id);
	try {
		var result = yield model.findOne({
			_id: id
		});
		return result._doc;
	} catch (e) {
		return e.toString();
	}
}

Dao.prototype.findByPid = function*(pid) {
	debug('dao findByPid, pid=' + pid);
	try {
		var result = yield model.find({
			pid: pid
		});
		return result;
	} catch (e) {
		return e.toString();
	}
}

module.exports = new Dao();